// eslint-disable-next-line @typescript-eslint/consistent-type-imports
/*
 * @Author: zy
 * @Date: 2021-10-21 10:05:09
 * @Last Modified by: zy
 * @Last Modified time: 2021-10-25 17:21:50
 */
import React, { useState, useEffect, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import {
  Card,
  Form,
  Select,
  Space,
  Row,
  Col,
  Button,
  Pagination,
  Switch,
  Popconfirm,
  message,
  Input,
} from 'antd';
import { formatDate } from '@/utils/utils';
import styles from './index.less';
import ProTable from '@ant-design/pro-table';
import type { ActionType } from '@ant-design/pro-table';
import Modal from './components/UserManageModal';
import {
  delUser,
  getUserList,
  getUserStateList,
  userInfo,
  changeState,
  downloadFile,
} from '@/services/user';
import type { UserStateDataType, OptionUserInfoDataType } from '@/services/user';

const UserManage = () => {
  const [form] = Form.useForm(); // 表单对象
  const pageSizeOptions = ['10', '20', '50']; //分页选择范围
  const ref = useRef<ActionType>(); //tableRef

  const [modalVisible, setmodalVisible] = useState(false); // 设置modal是否显示
  const [page, setPage] = useState<number>(1); // 设置当前页
  const [pageSize, setPageSize] = useState<number>(10); // 设置当前页记录条数

  const [total, setTotal] = useState<number>(); //查询记录数
  const [searchKey, setSearchKey] = useState<string>(); //设置搜索关键字
  const [stateId, setStateId] = useState<number>(); //设置图书类型aid

  const [modifyAid, setModifyAid] = useState<number>(-2); //设置数据的唯一标识（-1为新增,-2为初始化状态）
  const [dataSourceUserState, setDataSourceUserState] = useState<UserStateDataType>(); //设置搜索表单的状态
  const [modalData, setModalData] = useState<OptionUserInfoDataType | undefined>(); // 设置modal数据

  /**
   * @description: 获取用户信息（1、既可以返回所有数据，又可以根据aid进行查询；
   *                            2、设置modal的TreeData选择器的数据）
   */
  const getDataUserList = async (aid?: number) => {
    if (aid) {
      const params = { aid };
      const msg = await userInfo(params);
      setModalData(msg);
    }
  };

  /**
   * @description: 获取搜索表单用户状态
   */
  const getDataUserStateList = async () => {
    const msg = await getUserStateList();
    setDataSourceUserState(msg);
  };

  /**
   * @description: 打开页面时首次获取数据（用户信息和搜索表单的用户状态）
   */
  useEffect(() => {
    let mounted = true;
    if (mounted) {
      //Do Something
      getDataUserStateList();
    }
    return function cleanup() {
      mounted = false;
    };
  }, []);

  /**
   * @description: 页面数据刷新（根据modal是否显示、当前页、每页记录数的变化进行页面刷新）
   */
  useEffect(() => {
    let mounted = true;
    if (mounted) {
      //Do Something
      ref.current?.reload();
    }
    return function cleanup() {
      mounted = false;
    };
  }, [page, pageSize]);

  /**
   * @description: 页面刷新（根据新增修改modal的变化且处于关闭状态时进行页面刷新）
   */
  useEffect(() => {
    let mounted = true;
    if (mounted) {
      //Do Something
      if (!modalVisible) {
        ref.current?.reload();
      }
    }
    return function cleanup() {
      mounted = false;
    };
  }, [modalVisible]);

  /**
   * @description: 搜索表单提交（传入关键字数据并进行设置，刷新页面）
   */
  const onFinish = (values: { searchKey?: string }) => {
    if (values.searchKey) {
      setSearchKey(values.searchKey);
    }
    ref.current?.reload();
  };

  /**
   * @description: 重置表单(将关键字和状态id设置为空，重新渲染表单数据，刷新页面)
   */
  const onReset = () => {
    setSearchKey(undefined);
    setStateId(undefined);
    form.resetFields();
    ref.current?.reload();
  };

  /**
   * @description: 新增用户（1、设置modal显示；
   *                        2、设置传给modal数据为空；
   *                        3、设置操作判别；
   *                        4、重新获取分类信息）
   */
  const onInsert = () => {
    setmodalVisible(true);
    setModalData(undefined);
    setModifyAid(-1);
    getDataUserList();
  };

  /**
   * @description: table数据请求（判断searchKey是否存在值，渲染正常数据或查询数据，并进行信息提示）
   */
  const requestHandler = async () => {
    const params = { searchKey, stateId, page, pageSize };
    const msg = await getUserList(params);
    if (msg?.code === 10000) {
      setTotal(msg.data.rowNumber);
      return {
        data: msg?.data?.list,
        success: true,
        total: msg?.data.rowNumber,
      };
    } else {
      message.error(msg ? msg.message : '网络异常');
      return {
        data: undefined,
        success: false,
        total: 0,
      };
    }
  };

  /**
   * @description: 用户状态更改（传入数据调用接口传给后端，并刷新页面给出信息提示）
   */

  const OptionChangeState = async (aid: any) => {
    const body = { aid };
    console.log(aid);
    const msg = await changeState(body);
    if (msg.code === 10000) {
      message.success('更改成功');
    } else {
      message.error(msg ? msg.message : '操作失败，请进行刷新');
    }
  };

  const downFile = async (enclosureId: string) => {
    const params = { enclosureId };
    const msg = await downloadFile(params);
    if (msg.message) {
      message.success(msg.message);
    }
  };

  /**
   * @description: 分页设置（设置当前页和每页记录数）
   */
  const paginationChangeHandler = (_page: any, _pageSize: any) => {
    setPage(_page);
    setPageSize(_pageSize);
  };

  // ProTable列名
  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 140,
      height: 56,
      type: 'text',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 140,
      height: 56,
      type: 'number',
    },
    {
      title: '密码',
      dataIndex: 'password',
      key: 'password',
      width: 140,
      height: 56,
      type: 'text',
      render: () => {
        return <span>******</span>;
      },
    },
    {
      title: '是否启用',
      dataIndex: 'stateId',
      key: 'stateId',
      width: 160,
      height: 56,
      type: 'switch',
      render: (text: any, record: any) => {
        return (
          <Switch
            checkedChildren="是"
            unCheckedChildren="否"
            defaultChecked={record.stateName === '启用' ? true : false}
            onChange={() => {
              console.log('change');
              const aid = record.aid;
              OptionChangeState(aid);
            }}
          />
        );
      },
    },
    {
      title: '附件',
      dataIndex: 'enclosureId',
      key: 'enclosureId',
      width: 140,
      height: 56,
      render: (text: any, record: any) => {
        if (text != '-') {
          return (
            <div>
              <Button
                type="link"
                onClick={() => {
                  downFile(record.enclosureId);
                }}
              >
                {record.enclosureName}
              </Button>
            </div>
          );
        } else {
          return (
            <div>
              <Button
                type="link"
                onClick={() => {
                  message.info('暂无附件');
                }}
              >
                下载附件
              </Button>
            </div>
          );
        }
      },
    },
    {
      title: '新增日期',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 231,
      height: 56,
      render: (value: any) => {
        return formatDate(value, 2);
      },
    },
    {
      title: '操作',
      dataIndex: 'options',
      key: 'options',
      width: 183,
      height: 56,
      type: 'actions',
      render: (text: any, record: any) => (
        <div>
          <Button
            name="columnEdit"
            type="link"
            size="small"
            onClick={async () => {
              const aid = record.aid;
              await getDataUserList(aid);
              setModifyAid(aid);
              setmodalVisible(true);
            }}
          >
            修改
          </Button>
          <Popconfirm
            title="你确认要删除该项数据吗？"
            onConfirm={async () => {
              const params = {
                aid: record.aid,
              };
              const msg = await delUser(params);
              if (msg?.code === 10000) {
                ref.current?.reload();
                message.success('删除成功');
              } else {
                message.error(msg ? msg.message : '提交失败');
              }
            }}
            okText="确认"
            cancelText="取消"
          >
            <Button name="columnDelete" type="link" size="small">
              删除
            </Button>
          </Popconfirm>
        </div>
      ),
    },
  ];
  // 搜索表单
  const searchLayout = () => {
    return (
      <div key="searchLayout">
        <Form form={form} onFinish={onFinish} layout="inline">
          <Form.Item name="searchKey" key="searchKey" className={styles.searchKey}>
            <Space>
              <span>员工姓名：</span>
              <Input className={styles.searchLayoutInput} allowClear placeholder="请输入" />
            </Space>
          </Form.Item>
          <Form.Item name="stateId" key="state">
            <Space>
              <span>状态：</span>
              <Select
                className={styles.searchLayoutSelect}
                placeholder="请选择"
                allowClear
                onChange={(value: any) => {
                  setStateId(value);
                }}
              >
                {(dataSourceUserState?.data || []).map((data) => {
                  return (
                    <Select.Option key={data.id} value={data.id}>
                      {data.name}
                    </Select.Option>
                  );
                })}
              </Select>
            </Space>
          </Form.Item>
          <Form.Item className={styles.searchBtn}>
            <Space>
              <Button name="searchResert" htmlType="button" onClick={onReset}>
                重置
              </Button>
              <Button name="searchQuery" type="primary" htmlType="submit">
                查询
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
    );
  };

  // 分页
  const afterTableLayout = () => {
    return (
      <Row justify="end">
        <Col className={styles.tableToolbar}>
          <Pagination
            current={page}
            pageSize={pageSize}
            total={total}
            showSizeChanger
            pageSizeOptions={pageSizeOptions}
            onChange={paginationChangeHandler}
          />
        </Col>
      </Row>
    );
  };

  return (
    <PageContainer>
      <Card className={styles.cardStyle}>{searchLayout()}</Card>
      <Card>
        {/* {beforTableLayout()} */}
        <ProTable
          rowKey="aid"
          columns={columns}
          request={requestHandler}
          actionRef={ref}
          pagination={false}
          headerTitle={[
            <div key="tableTitle" className={styles.titleBox}>
              <span className={styles.titleText}>用户列表</span>
            </div>,
          ]}
          toolBarRender={() => [
            <Button name="columnAdd" type="primary" onClick={onInsert}>
              新增
            </Button>,
          ]}
          size="middle"
          search={false}
          options={{ fullScreen: true, setting: false, density: false }}
        />
        {afterTableLayout()}
      </Card>
      <Modal
        modifyAid={modifyAid}
        modalVisible={modalVisible}
        hideModal={() => {
          setmodalVisible(false);
        }}
        dataSource={modalData}
        resetModifyAid={() => {
          setModifyAid(-2);
        }}
      />
    </PageContainer>
  );
};

export default UserManage;
